package com.zuo.service.serviceImpl;

import com.zuo.entity.Doc;
import com.zuo.mapper.DocMapper;
import com.zuo.service.DocService;
import com.zuo.util.DateFormat;
import com.zuo.util.HrmConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author 白白旧维
 * @Date 2022/3/3 11:29
 */
@Service
@Transactional(readOnly = true)
public class DocServiceImpl implements DocService {

    @Autowired
    private DocMapper docMapper;

    @Override
    public List<Doc> listDoc() {
        List<Doc> docList = docMapper.listDoc();
        for (Doc doc:docList){
            doc.setCreateTime(DateFormat.format(doc.getDcreateTime()));
        }
        return docList;
    }

    @Override
    public List<Doc> searchDoc(String dtitle) {
        List<Doc> docList = docMapper.searchDoc(dtitle);
        for (Doc doc:docList){
            doc.setCreateTime(DateFormat.format(doc.getDcreateTime()));
        }
        return docList;
    }

    @Override
    public Doc getOne(int id) {
        return docMapper.getOne(id);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int updateDoc(Doc doc) {
        //删除原文件
        Doc doc1 = docMapper.getOne(doc.getDocid());
        File file = new File(HrmConstants.FILES+doc1.getDpath());
        if(file.exists()){
            file.delete();
        }
        return docMapper.updateDoc(doc);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int upload(Doc doc) {
        doc.setDcreateTime(new Date(System.currentTimeMillis()));
        return docMapper.upload(doc);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int deleteDocs(String ids) {
        System.out.println("ids = " + ids);
        String[] id = ids.split(",");
        int count=0;
        for (String i : id) {
            int docid=0;
            if(StringUtils.isNotBlank(i)){
                docid=Integer.parseInt(i);
            }
            //删除文件
            Doc doc = docMapper.getOne(docid);
            File file = new File(HrmConstants.FILES+doc.getDpath());
            if(file.exists()){
                file.delete();
            }
            int result = docMapper.deleteDoc(docid);
            if(result!=0){
                count++;
            }
        }
        if(count!=id.length){
            throw new RuntimeException("删除失败");
        }
        return count;
    }
}
